<template>
  <div class="tab-bar-container">
    <div class="tab-nav-buttons" v-if="tabList.length > 0">
      <el-button class="nav-button" @click="scrollTabs(-200)">
        <el-icon>
          <DArrowLeft />
        </el-icon>
      </el-button>
    </div>

    <div class="tab-scroll-container" ref="scrollContainer">
      <div class="tab-scroll-content" ref="scrollContent" @wheel.prevent="handleWheel">
        <el-tabs v-model="activeTab" type="card" closable @tab-click="handleTabClick" @tab-remove="handleTabRemove"
          v-if="tabList.length > 0">
          <el-tab-pane v-for="tab in tabList" :key="tab.path" :label="tab.title" :name="tab.path"
            :ref="el => setTabRef(el, tab.path)">
            <!-- 标签页内容通过router-view显示 -->
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <div class="tab-nav-buttons">
      <el-button class="nav-button" @click="scrollTabs(200)">
        <el-icon>
          <DArrowRight />
        </el-icon>
      </el-button>
      <div>
        <el-dropdown @command="handleCommand" trigger="click">
          <el-button class="nav-button" @click="">
            <el-icon>
              <Setting />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="closeOtherTabs">关闭其他页</el-dropdown-item>
              <el-dropdown-item command="closeAllTabs">关闭所有页</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTabs } from '@/store/tabs'
import { storeToRefs } from 'pinia'
import { ElTabs, ElTabPane, ElButton, ElIcon } from 'element-plus'

const router = useRouter()
const route = useRoute()
const tabsStore = useTabs()
const { activeTab, tabList } = storeToRefs(tabsStore)
const { closeTab, closeOtherTabs, closeAllTabs } = tabsStore

// 滚动相关引用
const scrollContainer = ref<HTMLDivElement | null>(null)
const scrollContent = ref<HTMLDivElement | null>(null)
const tabRefs = ref<Record<string, HTMLElement>>({})

watch(activeTab, () => {
  scrollToActiveTab()
})

// 计算是否可以向左/向右滚动
const canScrollLeft = computed(() => {
  return scrollContainer.value ? scrollContainer.value.scrollLeft > 0 : false
})

const canScrollRight = computed(() => {
  if (!scrollContainer.value) return false
  const container = scrollContainer.value
  return container.scrollLeft + container.clientWidth + 1 < container.scrollWidth
})

// 设置标签页引用
const setTabRef = (el: any, path: string) => {
  // 修复：确保获取到正确的DOM元素引用
  if (el) {
    // 如果el是Vue组件实例，获取其$el属性
    const element = el.$el || el
    // 确保element是一个有效的DOM元素
    if (element && typeof element.getBoundingClientRect === 'function') {
      tabRefs.value[path] = element
    }
  }
}

// 处理鼠标滚轮事件实现水平滚动
const handleWheel = (e: WheelEvent) => {
  if (scrollContainer.value && scrollContent.value) {
    const delta = e.deltaY || e.deltaX
    scrollContainer.value.scrollLeft += delta
  }
}

// 滚动标签页
const scrollTabs = (offset: number) => {
  if (scrollContainer.value) {
    scrollContainer.value.scrollBy({
      left: offset,
      behavior: 'smooth'
    })
  }
}

// 滚动到激活的标签页
const scrollToActiveTab = () => {
  nextTick(() => {
    if (scrollContainer.value && activeTab.value && tabRefs.value[activeTab.value]) {
      const container = scrollContainer.value
      const activeTabElement = tabRefs.value[activeTab.value]

      // 确保activeTabElement是一个有效的DOM元素
      if (container && activeTabElement && typeof activeTabElement.getBoundingClientRect === 'function') {
        const containerRect = container.getBoundingClientRect()
        const tabRect = activeTabElement.getBoundingClientRect()

        // 计算需要滚动的距离
        const scrollLeft = tabRect.left - containerRect.left + container.scrollLeft - container.clientWidth / 2 + tabRect.width / 2

        // 平滑滚动到目标位置
        container.scrollTo({
          left: scrollLeft,
          behavior: 'smooth'
        })
      }
    }
  })
}

// 处理标签页点击
const handleTabClick = (tab: any) => {
  // 修复：正确访问标签页的name属性
  const path = tab.paneName || tab.name || (tab.props ? tab.props.name : '')
  if (path && path !== decodeURIComponent(route.fullPath)) {
    router.push(path)
  }
}

// 处理标签页关闭
const handleTabRemove = (path: any) => {
  closeTab(path)

  // 如果关闭的是当前页面，需要跳转到另一个页面
  if (path === decodeURIComponent(route.fullPath)) {
    if (tabList.value.length > 0) {
      router.push(activeTab.value)
    } else {
      router.push(localStorage.getItem('firstPath') || '/')
    }
  }
}

// 组件挂载时添加事件监听器
const handleScroll = () => {
  // 滚动事件处理，用于更新按钮状态
  // 触发Vue的响应式更新
  canScrollLeft.value;
  canScrollRight.value;
}

const handleCommand = (command: string) => {
  switch (command) {
    case 'closeOtherTabs':
      closeOtherTabs(decodeURIComponent(route.fullPath))
      break
    case 'closeAllTabs':
      closeAllTabs()
      //打开默认页
      router.push(localStorage.getItem('firstPath') || '/')
      break
  }
}

onMounted(() => {
  // 监听滚动事件以更新按钮状态
  if (scrollContainer.value) {
    scrollContainer.value.addEventListener('scroll', handleScroll)
  }
})

// 组件卸载前移除事件监听器
onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
.tab-bar-container {
  display: flex;
  align-items: center;
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  padding: 0;
  position: relative;
}

/* 导航按钮 */
.tab-nav-buttons {
  display: flex;
  align-items: center;
}

.nav-button {
  padding: 8px;
  margin: 0 2px;
  border: 1px solid var(--el-border-color);
  background-color: var(--el-bg-color);
}

.nav-button:hover {
  background-color: var(--el-bg-color-page);
}

.nav-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 滚动容器 */
.tab-scroll-container {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

.tab-scroll-container::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}

.tab-scroll-content {
  display: inline-block;
  min-width: 100%;
}

/* 确保标签页正确显示 */
:deep(.el-tabs__header) {
  margin: 0;
}

:deep(.el-tabs__nav-wrap) {
  margin-bottom: 0;
}

:deep(.el-tabs--card>.el-tabs__header .el-tabs__item.is-active) {
  border-bottom-color: transparent
}

:deep(.el-tabs__item) {
  height: 32px;
  line-height: 32px;
  padding: 0 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {

  :deep(.el-tabs__item) {
    padding: 0 10px;
    font-size: 12px;
  }
}
</style>